/*
 * Copyright 2007-2012, Sualeh Fatehi <sualeh@hotmail.com>
 * 
 * This work is licensed under the Creative Commons Attribution 3.0 License. 
 * To view a copy of this license, visit 
 * http://creativecommons.org/licenses/by/3.0/ 
 * or send a letter to 
 * Creative Commons
 * 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
 */
package sf.event.controller;


import java.io.StringReader;
import java.util.Collection;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import sf.event.model.Event;
import sf.event.model.EventList;
import sf.event.service.EventService;

@Controller
public class EventRestController
{

  private static final String XML_VIEW_NAME = "events";

  @Autowired
  private EventService eventService;
  @Autowired
  private Jaxb2Marshaller jaxb2Mashaller;

  @RequestMapping(method = RequestMethod.DELETE, value = "/event/{id}")
  public ModelAndView deleteEvent(@PathVariable final String id)
  {

    eventService.delete(Long.parseLong(id));

    final Collection<Event> events = eventService.findAll();
    final EventList list = new EventList();
    list.addAll(events);

    return new ModelAndView(XML_VIEW_NAME, "events", list);
  }

  @RequestMapping(method = RequestMethod.GET, value = "/event/{id}", headers = "Accept=application/xml, application/json")
  public ModelAndView getEvent(@PathVariable final String id)
  {

    final Event event = eventService.find(Long.parseLong(id));

    return new ModelAndView(XML_VIEW_NAME, "object", event);
  }

  @RequestMapping(method = RequestMethod.GET, value = "/events", headers = "Accept=application/xml, application/json")
  public ModelAndView getEvents()
  {

    final Collection<Event> events = eventService.findAll();
    final EventList list = new EventList(events);

    return new ModelAndView(XML_VIEW_NAME, "events", list);
  }

  @RequestMapping(method = RequestMethod.PUT, value = "/event/{id}")
  public ModelAndView updateEvent(@RequestBody final String body)
  {

    final Source source = new StreamSource(new StringReader(body));
    final Event event = (Event) jaxb2Mashaller.unmarshal(source);
    eventService.update(event);

    return new ModelAndView(XML_VIEW_NAME, "object", event);
  }

}
